/*
 *
 *  *    Copyright 2020-2021 luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.core.utils;

import org.slf4j.Logger;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Map TheadLocal 工具类
 *
 * @author luter
 */
public abstract class AuthContextThreadUtil {
    /**
     * The constant log.
     */
    private static final transient Logger log = getLogger(AuthContextThreadUtil.class);
    /**
     * The constant MAP_THREAD_LOCAL.
     */
    private static final ThreadLocal<Map<Object, Object>> MAP_THREAD_LOCAL = new InheritableThreadLocalMap<>();

    /**
     * 获取 map.大小100
     *
     * @return the map
     */
    public static Map<Object, Object> getMap() {
        if (MAP_THREAD_LOCAL.get() == null) {
            return Collections.emptyMap();
        } else {
            return new HashMap<>(MAP_THREAD_LOCAL.get());
        }
    }

    /**
     * 设置 map.
     *
     * @param localMap the local map
     */
    public static void setMap(Map<Object, Object> localMap) {
        if (CollectionUtil.isEmpty(localMap)) {
            return;
        }
        ensureResourcesInitialized();
        MAP_THREAD_LOCAL.get().clear();
        MAP_THREAD_LOCAL.get().putAll(localMap);
    }


    /**
     * 获取
     *
     * @param key the key
     * @return the object
     */
    public static Object get(Object key) {
        if (log.isTraceEnabled()) {
            String msg = "get() - in thread [" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }
        Object value = getValue(key);
        if ((value != null) && log.isTraceEnabled()) {
            String msg = "Retrieved value of type [" + value.getClass().getName() + "] for key [" +
                    key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }
        return value;
    }


    /**
     * 存入
     *
     * @param key   the key
     * @param value the value
     */
    public static void put(Object key, Object value) {
        if (key == null) {
            throw new IllegalArgumentException("key cannot be null");
        }

        if (value == null) {
            remove(key);
            return;
        }

        ensureResourcesInitialized();
        MAP_THREAD_LOCAL.get().put(key, value);

        if (log.isTraceEnabled()) {
            String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" +
                    key + "] to thread " + "[" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }
    }

    /**
     * 删除
     *
     * @param key the key
     * @return the object
     */
    public static Object remove(Object key) {
        Map<Object, Object> perThreadResources = MAP_THREAD_LOCAL.get();
        Object value = perThreadResources != null ? perThreadResources.remove(key) : null;

        if ((value != null) && log.isTraceEnabled()) {
            String msg = "Removed value of type [" + value.getClass().getName() + "] for key [" +
                    key + "]" + "from thread [" + Thread.currentThread().getName() + "]";
            log.trace(msg);
        }

        return value;
    }

    /**
     * 清空ThreadLocal
     */
    public static void remove() {
        MAP_THREAD_LOCAL.remove();
    }

    /**
     * Gets value.
     *
     * @param key the key
     * @return the value
     */
    private static Object getValue(Object key) {
        Map<Object, Object> perThreadResources = MAP_THREAD_LOCAL.get();
        return perThreadResources != null ? perThreadResources.get(key) : null;
    }

    /**
     * Ensure resources initialized.
     */
    private static void ensureResourcesInitialized() {
        if (MAP_THREAD_LOCAL.get() == null) {
            MAP_THREAD_LOCAL.set(new HashMap<>());
        }
    }

    /**
     * The type Inheritable thread local map.
     *
     * @param <T> the type parameter
     * @author luter
     */
    private static final class InheritableThreadLocalMap<T extends Map<Object, Object>> extends InheritableThreadLocal<Map<Object, Object>> {
        @Override
        @SuppressWarnings({"unchecked"})
        protected Map<Object, Object> childValue(Map<Object, Object> parentValue) {
            if (parentValue != null) {
                return (Map<Object, Object>) ((HashMap<Object, Object>) parentValue).clone();
            } else {
                return null;
            }
        }
    }
}
